import axios from 'axios'
import { clearToken, getToken } from '@/utils/axios/token'
import router from '@/router'

const request = axios.create({
	baseURL: 'http://',
	timeout: 5000,
})

// 添加请求拦截器
request.interceptors.request.use(
	config => {
		const token = getToken()
		if (token) {
			config.headers.Authorization = `Bearer ${token}`
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

// 添加响应拦截器
request.interceptors.response.use(
	response => {
		// 2xx
		return response.data
	},
	error => {
		// 超出 2xx

		// 401 token失效
		if (error.response.status === 401) {
			clearToken()
			router.navigate('/login')
			window.location.reload()
		}
		return Promise.reject(error)
	}
)

export { request }
